package queueDemo;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

class DelayedTask implements Delayed {
    private final long startTime;
    private final String name;

    public DelayedTask(long startTime, String name) {
        this.startTime = startTime;
        this.name = name;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(startTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        return Long.compare(this.startTime, ((DelayedTask) o).startTime);
    }

    @Override
    public String toString() {
        return name;
    }
}

public class DelayQueueExample {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Delayed> queue = new DelayQueue<>();
        queue.put(new DelayedTask(System.currentTimeMillis() + 2000, "Task1"));
        queue.put(new DelayedTask(System.currentTimeMillis() + 1000, "Task2"));

        System.out.println(queue.take()); // 输出Task2
    }
}
